<?php

namespace app\index\controller;

use think\facade\Queue;

class QueueJob
{
    /**
     * 执行队列
     */
    public function doJob()
    {
        $handle_name = 'app\index\job\Task';
        $queue_name = 'task';
        $params = [
            'type' => 'test',
            'record_id' => 123,
        ];
        // 立即执行
        $pushed = Queue::push($handle_name, json_encode($params, JSON_UNESCAPED_UNICODE), $queue_name);
        var_dump($pushed); //cFWiWeKXXamLVWgycvXXghSUbqVjVLoD
        // 延迟5秒执行
        // $pushed = Queue::later(5, $handle_name, $params, $queue_name);
    }

    /**
     * 执行队列
     */
    public function queue()
    {
        //获取参数
        $data = file_get_contents("php://input");

        if (empty($data)) {
            echo "post is null";
        }
        $params = json_decode($data, true);

        /*创建新消息并推送到消息队列*/
        // 当前任务由哪个类负责处理
        $job_handler_classname = "app\index\job\Send";
        // 当前队列归属的队列名称
        $queue_name = "send_job_queue";
        // 当前任务所需的业务数据
        $job_data = ["ts" => time(), "uniqid" => uniqid(), "params" => $params];
        // 将任务推送到消息队列等待对应的消费者去执行
        $is_pushed = \think\facade\Queue::push($job_handler_classname, $job_data, $queue_name);
        // $is_pushed = \think\facade\Queue::later(3, $job_handler_classname, $job_data, $job_queue_name);

        if ($is_pushed == false) {
            echo 'send job queue went wrong';
            exit;
        }
        //操作成功
        echo 'success';
    }
}
